const puppeteer = require("puppeteer");
(async () => {
  let _argv = process.argv;
  if (_argv <= 2) {
    console.log("请指定网址!");
  } else {
    if (!_argv.find(v => v == "-u")) {
      console.log("请指定网址!");
    } else {
      let _time = 3000;
      let _output = "file";
      let _url = process.argv[_argv.findIndex(v => v == "-u") + 1];
      let _width = 1280;
      let _height = 720;
      let _size = "1280x720";
      if (_argv.find(v => v == "-t")) {
        _time = parseInt(process.argv[_argv.findIndex(v => v == "-t") + 1]);
      }
      if (_argv.find(v => v == "-o")) {
        _output = process.argv[_argv.findIndex(v => v == "-o") + 1];
        if (_output !== "base64") {
          _output = "file";
        }
      }
      if (_argv.find(v => v == "-size")) {
        if (process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")) {
          _size =
            process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[0] +
            "x" +
            parseInt(
              process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[1]
            );
          _width = parseInt(
            process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[0]
          );
          _height = parseInt(
            process.argv[_argv.findIndex(v => v == "-size") + 1].split("*")[1]
          );
        }
      }
      // 初始化模拟浏览器
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      // 设置宽高
      await page.setViewport({ width: _width, height: _height });
      try {
        await page.goto(_url);
        setTimeout(function() {
          if (_output == "file") {
            page.screenshot({
              path:
                "output/" +
                _url.split("//")[1] +
                "_t" +
                _time +
                "_size" +
                _size +
                ".jpg"
            });
            console.log(
              "生成图片路径为:" +
                __dirname +
                "\\output\\" +
                _url.split("//")[1] +
                "_t" +
                _time +
                "_size" +
                _size +
                ".jpg"
            );
          } else {
            page.screenshot({ encoding: "base64" }).then(function(res) {
              console.log("data:image/png;base64," + res);
            });
          }
        }, _time);
        setTimeout(function() {
          browser.close();
        }, _time + 1000);
        setTimeout(function() {
          process.exit();
        }, _time + 1100);
      } catch (err) {
        console.log(
          "无法获取的url地址,请确保目标能被访问且使用 http:// 或者 https:// 协议的格式!"
        );
        process.exit();
      }
    }
  }
})();
